package com.ilas.controller;

import com.ilas.aspect.DataSource;
import com.ilas.common.domain.AjaxResult;
import com.ilas.config.DynamicDataSourceContextHolder;
import com.ilas.entity.BizUser;
import com.ilas.entity.SysTenant;
import com.ilas.entity.TenantInfo;
import com.ilas.service.UserService;
import com.ilas.service.impl.TenantInfoServiceImpl;
import com.ilas.service.impl.TenantServiceImpl;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 租户控制层
 @author Luzck
 @date 2021/4/1 9:42 */
@Slf4j
@RestController
@RequestMapping("tenant")
public class TenantController {

    @Resource
    private TenantInfoServiceImpl tenantInfoService;

    @Resource
    private TenantServiceImpl tenantService;

    @Resource
    private UserService userService;

    /**
     * 旧版-租户-查询主数据库master中的所有租户的数据源数据列表
     * @return 所有租户的数据源数据列表
     */
    @RequestMapping("all")
    public List<TenantInfo> findAll() {
        DynamicDataSourceContextHolder.clearDataSourceKey();
        DynamicDataSourceContextHolder.setDataSourceKey("master");
        return tenantInfoService.findList();
    }

    /**
     * 旧版-租户-添加租户信息
     * @param tenant 租户信息
     * @return 所有租户信息
     */
    @RequestMapping("add")
    public List<TenantInfo> add(TenantInfo tenant) {
        System.out.println("before:" + DynamicDataSourceContextHolder.getDataSourceKey());
        // 旧版-需要手动创建数据库和数据库基础表，否则新增的数据源连不上；
        // 新版-如果想要实现自动创建可参考【新版-租户】相关接口。
        TenantInfo t = tenantInfoService.add(tenant);
        if (t != null) {
            DynamicDataSourceContextHolder.clearDataSourceKey();
            DynamicDataSourceContextHolder.setDataSourceKey(t.getTenantId());
        }
        System.out.println("after:" + DynamicDataSourceContextHolder.getDataSourceKey());

        List<BizUser> list = userService.getList();
        System.out.println(list.isEmpty());

        List<TenantInfo> tenantList = tenantInfoService.findList();
        log.info("{}", tenantList);
        return tenantList;
    }

    /**
     * 新版-租户-新增数据
     {
     "code": "test001",
     "name": "测试库001",
     "domainName": "localhost",
     "datasourceIp": "127.0.0.1",
     "datasourcePort": "3306",
     "datasourceUsername": "root",
     "datasourcePassword": "123456",
     "datasourceDriver": "com.mysql.cj.jdbc.Driver",
     "usageDays": 30
     }
     * @return AjaxResult
     */
    @PostMapping("add_v2")
    @DataSource
    public AjaxResult insert(@Validated @RequestBody SysTenant param) {
        if (StringUtils.isEmpty(param.getCode())) {
            return AjaxResult.error("租户编号不能为空");
        }
        if (StringUtils.isEmpty(param.getDatasourceIp())) {
            return AjaxResult.error("数据库ip不能为空");
        }
        if (StringUtils.isEmpty(param.getDatasourcePort())) {
            return AjaxResult.error("数据库端口号不能为空");
        }
        if (StringUtils.isEmpty(param.getName())) {
            return AjaxResult.error("租户名称不能为空");
        }
        if (StringUtils.isEmpty(param.getDomainName())) {
            return AjaxResult.error("租户名称不能为空");
        }
        if (null == param.getUsageDays()) {
            return AjaxResult.error("有效期不能为空");
        }
        //if (null == param.getTemplateId()) {
        //    return AjaxResult.error("租户菜单模板不能为空");
        //}
        if (tenantService.isExsiteCode(param.getCode())) {
            return AjaxResult.error("租户编号不能重复");
        }
        if (tenantService.findByName(param.getName())) {
            return AjaxResult.error("租户名称不能重复");
        }
        if (tenantService.findByDomainName(param.getDomainName())) {
            return AjaxResult.error("租户前端域名不能重复");
        }
        SysTenant sysTenant = null;
        try {
            sysTenant = tenantService.insert(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sysTenant == null) {
            return AjaxResult.error();
        }
        return AjaxResult.success(sysTenant);
    }

    /**
     * 新版-租户-加载全部数据
     *
     * @return 对象列表
     */
    @GetMapping("/all_v2")
    @DataSource
    public AjaxResult queryAll() {
        List<SysTenant> list = tenantService.queryAll();
        list.forEach((item) -> {
            //不暴露给前端
            item.setDatasourcePassword(null);
            item.setDatasourceUrl(null);
        });
        return AjaxResult.success(list);
    }

}
